package com.yilin.tms.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yilin.commons.encrypt.EncryptUtils;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.commons.base.BaseAuth;
import com.yilin.tms.core.commons.base.BaseEntity;
import com.yilin.tms.core.commons.model.AuthData;
import com.yilin.tms.core.commons.model.AuthStatus;
import com.yilin.tms.core.commons.model.AuthStatusData;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.commons.utils.QueryUtil;
import com.yilin.tms.core.entity.truck.TransportLicense;
import com.yilin.tms.core.entity.truck.TravelLicense;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.OrganType;
import com.yilin.tms.core.entity.user.RoleType;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.auth.*;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.core.remote.IMessageRemote;
import com.yilin.tms.core.remote.IOrderRemote;
import com.yilin.tms.user.mapper.auth.*;
import com.yilin.tms.user.service.IAccountService;
import com.yilin.tms.user.service.IAuthService;
import com.yilin.tms.user.mapper.AccountMapper;
import com.yilin.tms.user.mapper.OrganizeMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 认证服务
 *
 * @author zhangjinyuan
 * @date 2022/10/26
 */
@Service
public class AuthService implements IAuthService {
    @Resource
    IAccountService accountService;
    @Resource
    IMessageRemote messageRemote;

    @Resource
    BusinessLicenseMapper businessLicenseMapper;
    @Resource
    DrivingLicenseMapper drivingLicenseMapper;
    @Resource
    IdCardMapper idCardMapper;
    @Resource
    QualificationCertMapper qualificationCertMapper;
    @Resource
    TransBusinessLicenseMapper transBusinessLicenseMapper;
    @Resource
    StampPersonalSignetMapper stampPersonalSignetMapper;
    @Resource
    StampCompanySealMapper stampCompanySealMapper;
    @Resource
    TaxCertificationMapper taxCertificationMapper;
    @Resource
    OrganizeMapper organizeMapper;
    @Resource
    AccountMapper accountMapper;
    @Resource
    IOrderRemote orderRemote;
    // 提取公用的条件应用方法
    private <T> void applyQueryWrapperConditions(QueryWrapper<T> targetWrapper, QueryWrapper<BaseEntity> sourceWrapper) {
        targetWrapper.or(wrapper -> wrapper.apply(sourceWrapper.getSqlSegment(), sourceWrapper.getParamNameValuePairs()));
    }
    /**
     * 获取认证分页
     */
    @Override
    public PageData<? extends BaseAuth> getAuthPage(Account loginUser, AuthData.AuthItem authItem, BaseEntity query, Integer start, Integer limit) {
        if (loginUser.getUserType() != UserType.platformUser&&loginUser.getUserType()!=UserType.adminUser) {
            query.setQuery(query.getQuery() + "&organizeId=" + loginUser.getOrganizeId());
        }
        PageData<? extends BaseAuth> page = null;
        switch (authItem) {
            case authIdCard:
                page = idCardMapper.selectPage(new PageData<>(start, limit), QueryUtil.andQueryWrapper(new QueryWrapper<>(), query.toQuery(IdCard.class)));
                break;
            case authBusinessLicense:
                page = businessLicenseMapper.selectPage(new PageData<>(start, limit), QueryUtil.andQueryWrapper(new QueryWrapper<>(), query.toQuery(BusinessLicense.class)));
                break;
            case authDrivingLicense:
                page = drivingLicenseMapper.selectPage(new PageData<>(start, limit), QueryUtil.andQueryWrapper(new QueryWrapper<>(), query.toQuery(DrivingLicense.class)));
                break;
            case authTransBusinessLicense:
                page = transBusinessLicenseMapper.selectPage(new PageData<>(start, limit), QueryUtil.andQueryWrapper(new QueryWrapper<>(), query.toQuery(TransBusinessLicense.class)));
                break;
            case authQualificationCert:
                page = qualificationCertMapper.selectPage(new PageData<>(start, limit), QueryUtil.andQueryWrapper(new QueryWrapper<>(), query.toQuery(QualificationCert.class)));
                break;
            case authCompanySealStamp:
                page = stampCompanySealMapper.selectPage(new PageData<>(start, limit), QueryUtil.andQueryWrapper(new QueryWrapper<>(), query.toQuery(StampCompanySeal.class)));
                break;
            case authPersonalSignetStamp:
                page = stampPersonalSignetMapper.selectPage(new PageData<>(start, limit), QueryUtil.andQueryWrapper(new QueryWrapper<>(), query.toQuery(StampPersonalSignet.class)));
                break;
            case authTaxCertification:
                page = taxCertificationMapper.selectPage(new PageData<>(start, limit), QueryUtil.andQueryWrapper(new QueryWrapper<>(), query.toQuery(TaxCertification.class)));
                break;
            default:
                break;
        }
        if (page == null) return null;
        return authPageDecrypt(page);
    }

    /**
     * 获取用户认证数据
     */
    @Override
    public List<AuthData> getUserAuthData(Account account) {
        Organize organize = organizeMapper.selectById(account.getOrganizeId());
        List<AuthData> authOptionList = new ArrayList<>();
        if (account.getUserType() == UserType.shipperUser || account.getUserType() == UserType.truckerUser) {
            // #### 身份证认证【必须】
            IdCard idCard = getIdCardByUserId(account.getId());
            authOptionList.add(new AuthData(AuthData.AuthItem.authIdCard, idCard));
            // #### 司机需要认证 驾驶证 从业证
            if (account.getUserType() == UserType.truckerUser) {
                // #### 驾驶证
                DrivingLicense drivingLicense = getDrivingLicenseByUserId(account.getId());
                authOptionList.add(new AuthData(AuthData.AuthItem.authDrivingLicense, drivingLicense));
                // #### 从业证
                QualificationCert qualificationCert = getQualificationCertByUserId(account.getId());
                authOptionList.add(new AuthData(AuthData.AuthItem.authQualificationCert, qualificationCert));
            }
            // 管理員 企业【营业执照+ 印章】 物流企业必【营业执照+ 印章+运输经营许可证】个体【签名 】
            if (account.getRoleType() == RoleType.manager) {
                if (organize.getOrganType() != OrganType.individual) {
                    BusinessLicense businessLicense = getBusinessLicenseByOrganizeId(organize.getId());
                    authOptionList.add(new AuthData(AuthData.AuthItem.authBusinessLicense, businessLicense));
                    if (organize.getUserType() == UserType.truckerUser) {
                        TransBusinessLicense transBusinessLicense = getTransLicenseByOrganizeId(organize.getId());
                        authOptionList.add(new AuthData(AuthData.AuthItem.authTransBusinessLicense, transBusinessLicense));
                    }
                    StampCompanySeal stampCompanySeal = getStampCompanySealByOrganizeId(organize.getId());
                    authOptionList.add(new AuthData(AuthData.AuthItem.authCompanySealStamp, stampCompanySeal));
                } else {
                    StampPersonalSignet stampPersonalSignet = getStampPersonalSignetByOrganizeId(organize.getId());
                    authOptionList.add(new AuthData(AuthData.AuthItem.authPersonalSignetStamp, stampPersonalSignet));
                    if (account.getUserType() == UserType.truckerUser) {
                        TaxCertification taxCertification = getTaxCertificationByOrganizeId(organize.getId());
                        authOptionList.add(new AuthData(AuthData.AuthItem.authTaxCertification, taxCertification));
                    }
                }
            }
        } else if (account.getUserType() == UserType.platformUser) {
            if (account.getRoleType() == RoleType.manager) {
                //营业执照
                BusinessLicense businessLicense = getBusinessLicenseByOrganizeId(organize.getId());
                authOptionList.add(new AuthData(AuthData.AuthItem.authBusinessLicense, businessLicense));
                //平台合同专用章
                StampCompanySeal stampCompanySeal = getStampCompanySealByOrganizeId(organize.getId());
                authOptionList.add(new AuthData(AuthData.AuthItem.authCompanySealStamp, stampCompanySeal));
            }
        }
//        } else if (account.getUserType() == UserType.zoneUser) {
//            //营业执照
//            BusinessLicense businessLicense = getBusinessLicenseByOrganizeId(organize.getId());
//            authOptionList.add(new AuthData(AuthData.AuthItem.authBusinessLicense, businessLicense));
//        }
        return authOptionList;
    }

    /**
     * 获取用户认证状态
     */
    @Override
    public List<AuthStatusData> getUserAuthStatus(Account account) {
        Organize organize = organizeMapper.selectById(account.getOrganizeId());
        List<AuthStatusData> authStatusList = new ArrayList<>();
        if (account.getUserType() == UserType.shipperUser || account.getUserType() == UserType.truckerUser) {
            // #### 身份证认证【必须】
            IdCard idCard = getIdCardByUserId(account.getId());
            authStatusList.add(new AuthStatusData(AuthData.AuthItem.authIdCard, idCard));
            // #### 司机需要认证 驾驶证 从业证
            if (account.getUserType() == UserType.truckerUser) {
                // #### 驾驶证
                DrivingLicense drivingLicense = getDrivingLicenseByUserId(account.getId());
                authStatusList.add(new AuthStatusData(AuthData.AuthItem.authDrivingLicense, drivingLicense));
                // #### 从业证
                QualificationCert qualificationCert = getQualificationCertByUserId(account.getId());
                authStatusList.add(new AuthStatusData(AuthData.AuthItem.authQualificationCert, qualificationCert));
            }
            // 管理員 企业【营业执照+ 印章】 物流企业必【营业执照+ 印章+运输经营许可证】个体【签名 】
            if (account.getRoleType() == RoleType.manager) {
                if (organize.getOrganType() != OrganType.individual) {
                    BusinessLicense businessLicense = getBusinessLicenseByOrganizeId(organize.getId());
                    authStatusList.add(new AuthStatusData(AuthData.AuthItem.authBusinessLicense, businessLicense));
                }
                if (organize.getOrganType() != OrganType.individual && organize.getUserType() == UserType.truckerUser) {
                    TransBusinessLicense transBusinessLicense = getTransLicenseByOrganizeId(organize.getId());
                    authStatusList.add(new AuthStatusData(AuthData.AuthItem.authTransBusinessLicense, transBusinessLicense));
                }
                if (organize.getOrganType() == OrganType.individual) {
                    StampPersonalSignet stampPersonalSignet = getStampPersonalSignetByOrganizeId(organize.getId());
                    authStatusList.add(new AuthStatusData(AuthData.AuthItem.authPersonalSignetStamp, stampPersonalSignet));
                } else {
                    StampCompanySeal stampCompanySeal = getStampCompanySealByOrganizeId(organize.getId());
                    authStatusList.add(new AuthStatusData(AuthData.AuthItem.authCompanySealStamp, stampCompanySeal));
                }
            }
        } else if (account.getUserType() == UserType.platformUser) {
            if (account.getRoleType() == RoleType.manager) {
                //营业执照
                BusinessLicense businessLicense = getBusinessLicenseByOrganizeId(organize.getId());
                authStatusList.add(new AuthStatusData(AuthData.AuthItem.authBusinessLicense, businessLicense));
                //平台合同专用章
                StampCompanySeal stampCompanySeal = getStampCompanySealByOrganizeId(organize.getId());
                authStatusList.add(new AuthStatusData(AuthData.AuthItem.authCompanySealStamp, stampCompanySeal));
            }
        }
//        else if (account.getUserType() == UserType.zoneUser) {
//            //营业执照
//            BusinessLicense businessLicense = getBusinessLicenseByOrganizeId(organize.getId());
//            authStatusList.add(new AuthStatusData(AuthData.AuthItem.authBusinessLicense, businessLicense));
//        }
        return authStatusList;
    }

    /**
     * 验证用户认证
     */
    @Override
    public void checkAuthStatus(Account account, Account loginUser, AuthData.AuthItem authItem) {
        boolean isCallMe = account.getId().equals(loginUser.getId());
        switch (authItem) {
            case authIdCard:
                IdCard card = getIdCardByUserId(account.getId());
                AuthData.checkAuth(card, authItem, isCallMe ? "您" : account.getName(), isCallMe);
                break;
            case authBusinessLicense:
                if (account.getOrganType() != OrganType.individual) {
                    BusinessLicense businessLicense = getBusinessLicenseByOrganizeId(account.getOrganizeId());
                    AuthData.checkAuth(businessLicense, authItem, isCallMe ? "您" : account.getOrganizeName(), isCallMe);
                }
                break;
            case authDrivingLicense:
                if (account.getUserType() == UserType.truckerUser) {
                    DrivingLicense drivingLicense = getDrivingLicenseByUserId(account.getId());
                    AuthData.checkAuth(drivingLicense, authItem, isCallMe ? "您" : account.getName(), isCallMe);
                }
                break;
            case authTransBusinessLicense:
                if (account.getOrganType() != OrganType.individual) {
                    TransBusinessLicense transBusinessLicense = getTransLicenseByOrganizeId(account.getOrganizeId());
                    AuthData.checkAuth(transBusinessLicense, authItem, isCallMe ? "您" : account.getOrganizeName(), isCallMe);
                }
                break;
            case authQualificationCert:
                if (account.getUserType() == UserType.truckerUser) {
                    QualificationCert qualificationCert = getQualificationCertByUserId(account.getId());
                    AuthData.checkAuth(qualificationCert, authItem, isCallMe ? "您" : account.getName(), isCallMe);
                }
                break;
            case authCompanySealStamp:
                if (account.getOrganType() != OrganType.individual) {
                    StampCompanySeal companySealStamp = getStampCompanySealByOrganizeId(account.getOrganizeId());
                    AuthData.checkAuth(companySealStamp, authItem, isCallMe ? "您" : account.getOrganizeName(), isCallMe);
                }
                break;
            case authPersonalSignetStamp:
                if (account.getOrganType() == OrganType.individual) {
                    StampPersonalSignet stampPersonalSignet = getStampPersonalSignetByOrganizeId(account.getOrganizeId());
                    AuthData.checkAuth(stampPersonalSignet, authItem, isCallMe ? "您" : account.getOrganizeName(), isCallMe);
                }
                break;
            case authTaxCertification:
                if (account.getOrganType() == OrganType.individual && account.getUserType() == UserType.truckerUser) {
                    TaxCertification taxCertification = getTaxCertificationByOrganizeId(account.getOrganizeId());
                    AuthData.checkAuth(taxCertification, authItem, isCallMe ? "您" : account.getOrganizeName(), isCallMe);
                }
                break;
        }
    }

    /**
     * 查找：获取用户身份证
     */
    @Override
    public IdCard getIdCardByUserId(String accountId) {
        IdCard idCard = idCardMapper.selectOne(new QueryWrapper<IdCard>().eq("account_id", accountId));
        if (idCard == null) return null;
        idCard.setIdCardNo(EncryptUtils.aesDecrypt(idCard.getIdCardNo(), null));
        return idCard;
    }

    /**
     * 查找：根据身份证号获取用户身份证
     */
    @Override
    public IdCard getIdCardByIdCardNo(String idCardNo) {
        IdCard idCard = idCardMapper.selectOne(new QueryWrapper<IdCard>().eq("id_card_no", EncryptUtils.aesEncrypt(idCardNo, null)));
        if (idCard == null) return null;
        idCard.setIdCardNo(EncryptUtils.aesDecrypt(idCard.getIdCardNo(), null));
        return idCard;
    }

    /**
     * 查找：获取电子签名
     */
    @Override
    public StampPersonalSignet getStampPersonalSignetByOrganizeId(String organizeId) {
        QueryWrapper<StampPersonalSignet> queryWrapper = new QueryWrapper<StampPersonalSignet>().eq("organize_id", organizeId);
        return stampPersonalSignetMapper.selectOne(queryWrapper);
    }

    /**
     * 查找：获取电子印章
     */
    @Override
    public StampCompanySeal getStampCompanySealByOrganizeId(String organizeId) {
        QueryWrapper<StampCompanySeal> queryWrapper = new QueryWrapper<StampCompanySeal>().eq("organize_id", organizeId);
        return stampCompanySealMapper.selectOne(queryWrapper);
    }

    /**
     * 查找：获取税务认证
     */
    @Override
    public TaxCertification getTaxCertificationByOrganizeId(String organizeId) {
        QueryWrapper<TaxCertification> queryWrapper = new QueryWrapper<TaxCertification>().eq("organize_id", organizeId);
        return taxCertificationMapper.selectOne(queryWrapper);
    }

    /**
     * 获取驾驶证
     */
    @Override
    public DrivingLicense getDrivingLicenseByUserId(String accountId) {
        DrivingLicense drivingLicense = drivingLicenseMapper.selectOne(new QueryWrapper<DrivingLicense>().eq("account_id", accountId));
        if (drivingLicense == null) return null;
        drivingLicense.setDrivingLicenseNo(EncryptUtils.aesDecrypt(drivingLicense.getDrivingLicenseNo(), null));
        return drivingLicense;
    }

    /**
     * 获取从业资格证
     */
    @Override
    public QualificationCert getQualificationCertByUserId(String accountId) {
        QualificationCert qualificationCert = qualificationCertMapper.selectOne(new QueryWrapper<QualificationCert>().eq("account_id", accountId));
        if (qualificationCert == null) return null;
        qualificationCert.setOccupationalRequirementsNo(EncryptUtils.aesDecrypt(qualificationCert.getOccupationalRequirementsNo(), null));
        return qualificationCert;
    }

    /**
     * 获取营业执照
     */
    @Override
    public BusinessLicense getBusinessLicenseByOrganizeId(String organizeId) {
        BusinessLicense businessLicense = businessLicenseMapper.selectOne(new QueryWrapper<BusinessLicense>().eq("organize_id", organizeId));
        if (businessLicense == null) return null;
        businessLicense.setBusinessNo(EncryptUtils.aesDecrypt(businessLicense.getBusinessNo(), null));
        businessLicense.setLegalCardNo(EncryptUtils.aesDecrypt(businessLicense.getLegalCardNo(), null));
        return businessLicense;
    }

    /**
     * 获取道路经营许可证
     */
    @Override
    public TransBusinessLicense getTransLicenseByOrganizeId(String organizeId) {
        TransBusinessLicense transBusinessLicense = transBusinessLicenseMapper.selectOne(new QueryWrapper<TransBusinessLicense>().eq("organize_id", organizeId));
        if (transBusinessLicense == null) return null;
        transBusinessLicense.setTransBusinessLicenseNo(EncryptUtils.aesDecrypt(transBusinessLicense.getTransBusinessLicenseNo(), null));
        return transBusinessLicense;
    }


    //-----------------------------------------------------证件保存---------------------------------------------------------

    /**
     * 保存和修改身份证
     */
    @Override
    public void saveIdCardAuth(Account loginUser, IdCard idCard) {
        if (idCard.getIdCardNo() != null)
            idCard.setIdCardNo(EncryptUtils.aesEncrypt(idCard.getIdCardNo(), null)); //TODO:加密身份证号
        idCard.setAccountId(loginUser.getId());
        idCard.setAccountName(idCard.getName());
        idCard.setOrganizeId(loginUser.getOrganizeId());
        idCard.setOrganizeName(loginUser.getOrganizeName());
        if (loginUser.getSuperiorPlatId() != null) {
            idCard.setSuperiorPlatId(loginUser.getSuperiorPlatId());
            idCard.setSuperiorPlatName(loginUser.getSuperiorPlatName());
        }
        idCard.setAuthStatus(AuthStatus.waitProcess);
        //恢复已删除可匹配的证件数据
        restoreLogicIdCardByNo(idCard);
        if (idCard.getId() != null) {
            IdCard oldIdCard = idCardMapper.selectById(idCard.getId());
            idCard.setOldIdCardNo(EncryptUtils.aesDecrypt(oldIdCard.getIdCardNo(), null));
            idCard.setUpdateUserId(loginUser.getId());
            idCard.setUpdateTime(new Date());
            idCardMapper.updateById(idCard);
        } else {
            idCard.setAddUserId(loginUser.getId());
            idCard.setCreateTime(new Date());
            idCardMapper.insert(idCard);
        }
        //更新账户数据
        Organize organize = organizeMapper.selectById(loginUser.getOrganizeId());
        if (organize.getManagerUserId().equals(loginUser.getId())) {
            if (loginUser.getOrganType() == OrganType.individual) {
                organize.setOrganizeName(idCard.getName() + "（个体）");
                organize.setOrganizeTel(loginUser.getPhone());
            }
            organize.setManagerUserName(idCard.getName());
            organizeMapper.updateById(organize);
        }
        loginUser.setOrganizeName(organize.getOrganizeName());
        loginUser.setName(idCard.getName());
        loginUser.setAddress(idCard.getAddress());
        accountMapper.updateById(loginUser);
    }

    /**
     * 保存营业执照认证数据
     */
    @Override
    public void saveBusinessLicenseAuth(Account loginUser, BusinessLicense businessLicense) {
        Organize organize = organizeMapper.selectById(loginUser.getOrganizeId());
        if (businessLicense.getValidityEndDate() != null) {
            businessLicense.setWarnDate(DateTimeUtil.plusDay(businessLicense.getValidityEndDate(), -30));
            businessLicense.setExpireDate(DateTimeUtil.plusDay(businessLicense.getValidityEndDate(), -3));
            businessLicense.setNoticeDate(DateTimeUtil.plusDay(businessLicense.getValidityEndDate(), -31));
        }
        if (businessLicense.getBusinessNo() != null) {
            //TODO:【加密执照编号】
            businessLicense.setBusinessNo(EncryptUtils.aesEncrypt(businessLicense.getBusinessNo(), null));
        }
        if (businessLicense.getLegalCardNo() != null) {
            //TODO:【加密法人证件号】
            businessLicense.setLegalCardNo(EncryptUtils.aesEncrypt(businessLicense.getLegalCardNo(), null));
        }
        businessLicense.setOrganizeId(organize.getId());
        businessLicense.setOrganizeName(organize.getOrganizeName());
        if (loginUser.getSuperiorPlatId() != null) {
            businessLicense.setSuperiorPlatId(loginUser.getSuperiorPlatId());
            businessLicense.setSuperiorPlatName(loginUser.getSuperiorPlatName());
        }
        businessLicense.setAuthStatus(AuthStatus.waitProcess);
        //恢复已删除可匹配的证件数据
        restoreLogicBusinessLicenseByNo(businessLicense);
        if (businessLicense.getId() != null) {
            BusinessLicense oldBusinessLicense = businessLicenseMapper.selectById(businessLicense.getId());
            oldBusinessLicense.setOldBusinessNo(EncryptUtils.aesDecrypt(oldBusinessLicense.getOldBusinessNo(), null));
            businessLicense.setUpdateUserId(loginUser.getId());
            businessLicense.setUpdateTime(new Date());
            businessLicenseMapper.updateById(businessLicense);
        } else {
            businessLicense.setAddUserId(loginUser.getId());
            businessLicense.setCreateTime(new Date());
            businessLicenseMapper.insert(businessLicense);
        }
        //更新组织数据
        organize.setOrganizeName(businessLicense.getName());
        organize.setAddress(businessLicense.getCompanyAddress());
        organize.setOrganizeTel(businessLicense.getBusinessTel());
        organize.setLegalName(businessLicense.getLegalName());
        organize.setLegalPhone(null);
        organizeMapper.updateById(organize);
        //保存账户数据
        loginUser.setOrganizeName(organize.getOrganizeName());
        accountMapper.updateById(loginUser);
    }

    /**
     * 保存道路运输经营许可证认证数据
     */
    @Override
    public void saveTransBusinessLicenseAuth(Account loginUser, TransBusinessLicense transBusinessLicense) {
        Organize organize = organizeMapper.selectById(loginUser.getOrganizeId());
        if (transBusinessLicense.getTransBusinessLicenseNo() != null) {
            //TODO:【加密经营许可证证号】
            transBusinessLicense.setTransBusinessLicenseNo(EncryptUtils.aesEncrypt(transBusinessLicense.getTransBusinessLicenseNo(), null));
        }
        transBusinessLicense.setOrganizeId(organize.getId());
        transBusinessLicense.setOrganizeName(organize.getOrganizeName());
        transBusinessLicense.setAuthStatus(AuthStatus.waitProcess);
        if (loginUser.getSuperiorPlatId() != null) {
            transBusinessLicense.setSuperiorPlatId(loginUser.getSuperiorPlatId());
            transBusinessLicense.setSuperiorPlatName(loginUser.getSuperiorPlatName());
        }
        //恢复已删除可匹配的证件数据
        restoreLogicTransBusinessLicenseByNo(transBusinessLicense);
        if (transBusinessLicense.getId() == null) {
            transBusinessLicense.setAddUserId(loginUser.getId());
            transBusinessLicense.setCreateTime(new Date());
            transBusinessLicenseMapper.insert(transBusinessLicense);
        } else {
            transBusinessLicense.setAddUserId(loginUser.getId());
            transBusinessLicense.setCreateTime(new Date());
            transBusinessLicenseMapper.updateById(transBusinessLicense);
        }
    }

    /**
     * 保存驾驶证认证数据
     */
    @Override
    public void saveDrivingLicenseAuth(Account loginUser, DrivingLicense drivingLicense) {
        if (drivingLicense.getDrivingLicenseNo() != null) {
            //TODO:【加密驾驶证号】
            drivingLicense.setDrivingLicenseNo(EncryptUtils.aesEncrypt(drivingLicense.getDrivingLicenseNo(), null));
        }
        drivingLicense.setAccountId(loginUser.getId());
        drivingLicense.setAccountName(loginUser.getName());
        drivingLicense.setAuthStatus(AuthStatus.waitProcess);
        drivingLicense.setOrganizeId(loginUser.getId());
        drivingLicense.setOrganizeName(loginUser.getOrganizeName());
        if (loginUser.getSuperiorPlatId() != null) {
            drivingLicense.setSuperiorPlatId(loginUser.getSuperiorPlatId());
            drivingLicense.setSuperiorPlatName(loginUser.getSuperiorPlatName());
        }
        //恢复已删除可匹配的证件数据
        restoreLogicDrivingLicenseByNo(drivingLicense);
        if (drivingLicense.getId() == null) {
            drivingLicense.setAddUserId(loginUser.getId());
            drivingLicense.setCreateTime(new Date());
            drivingLicenseMapper.insert(drivingLicense);
        } else {
            drivingLicense.setUpdateUserId(loginUser.getId());
            drivingLicense.setUpdateTime(new Date());
            drivingLicenseMapper.updateById(drivingLicense);
        }
    }

    /**
     * 保存从业资格证认证数据
     */
    @Override
    public void saveQualificationCertAuth(Account loginUser, QualificationCert qualificationCert) {
        if (qualificationCert.getOccupationalRequirementsNo() != null) {
            //TODO:【加密从业资格证证号】
            qualificationCert.setOccupationalRequirementsNo(EncryptUtils.aesEncrypt(qualificationCert.getOccupationalRequirementsNo(), null));
        }
        qualificationCert.setAccountId(loginUser.getId());
        qualificationCert.setAccountName(loginUser.getName());
        qualificationCert.setAuthStatus(AuthStatus.waitProcess);
        qualificationCert.setOrganizeId(loginUser.getId());
        qualificationCert.setOrganizeName(loginUser.getOrganizeName());
        if (loginUser.getSuperiorPlatId() != null) {
            qualificationCert.setSuperiorPlatId(loginUser.getSuperiorPlatId());
            qualificationCert.setSuperiorPlatName(loginUser.getSuperiorPlatName());
        }
        //恢复已删除可匹配的证件数据
        restoreLogicQualificationCertByNo(qualificationCert);
        if (qualificationCert.getId() == null) {
            qualificationCert.setAddUserId(loginUser.getId());
            qualificationCert.setCreateTime(new Date());
            qualificationCertMapper.insert(qualificationCert);
        } else {
            qualificationCert.setUpdateUserId(loginUser.getId());
            qualificationCert.setUpdateTime(new Date());
            qualificationCertMapper.updateById(qualificationCert);
        }
    }

    /**
     * 保存企业印章
     */
    @Override
    public void saveStampCompanySealAuth(Account loginUser, StampCompanySeal stampCompanySeal) {
        Organize organize = organizeMapper.selectById(loginUser.getOrganizeId());
        stampCompanySeal.setOrganizeName(organize.getOrganizeName());
        if (loginUser.getSuperiorPlatId() != null) {
            stampCompanySeal.setSuperiorPlatId(loginUser.getSuperiorPlatId());
            stampCompanySeal.setSuperiorPlatName(loginUser.getSuperiorPlatName());
        }
        stampCompanySeal.setAuthStatus(AuthStatus.waitProcess);
        //恢复已删除可匹配的证件数据
        restoreLogicStampCompanySeal(stampCompanySeal);
        if (stampCompanySeal.getId() == null) {
            stampCompanySeal.setOrganizeId(loginUser.getOrganizeId());
            stampCompanySeal.setAddUserId(loginUser.getId());
            stampCompanySeal.setCreateTime(new Date());
            stampCompanySealMapper.insert(stampCompanySeal);
        } else {
            stampCompanySeal.setUpdateUserId(loginUser.getId());
            stampCompanySeal.setUpdateTime(new Date());
            stampCompanySealMapper.updateById(stampCompanySeal);
        }
        //更新组织数据
        organize.setSignatureImg(stampCompanySeal.getCompanySeal());
        organize.setSignatureId(stampCompanySeal.getId());
        organizeMapper.updateById(organize);
    }

    /**
     * 保存个人签名
     */
    @Override
    public void saveStampPersonalSignetAuth(Account loginUser, StampPersonalSignet stampPersonalSignet) {
        Organize organize = organizeMapper.selectById(loginUser.getOrganizeId());
        stampPersonalSignet.setOrganizeName(organize.getOrganizeName());
        if (loginUser.getSuperiorPlatId() != null) {
            stampPersonalSignet.setSuperiorPlatId(loginUser.getSuperiorPlatId());
            stampPersonalSignet.setSuperiorPlatName(loginUser.getSuperiorPlatName());
        }
        stampPersonalSignet.setAuthStatus(AuthStatus.waitProcess);
        //恢复已删除可匹配的证件数据
        restoreLogicStampPersonalSignet(stampPersonalSignet);
        if (stampPersonalSignet.getId() == null) {
            stampPersonalSignet.setAddUserId(loginUser.getId());
            stampPersonalSignet.setCreateTime(new Date());
            stampPersonalSignet.setOrganizeId(loginUser.getOrganizeId());
            stampPersonalSignetMapper.insert(stampPersonalSignet);
        } else {
            stampPersonalSignet.setUpdateUserId(loginUser.getId());
            stampPersonalSignet.setUpdateTime(new Date());
            stampPersonalSignetMapper.updateById(stampPersonalSignet);
        }
        //更新组织数据
        organize.setSignatureImg(stampPersonalSignet.getPersonalSignet());
        organize.setSignatureId(stampPersonalSignet.getId());
        organizeMapper.updateById(organize);
    }

    /**
     * 保存税务
     */
    @Override
    public void saveTaxCertificationAuth(Account loginUser, TaxCertification taxCertification) {
        Organize organize = organizeMapper.selectById(loginUser.getOrganizeId());
        if (loginUser.getUserType() == UserType.shipperUser)
            throw new BusinessException("ShipperUser not TaxCertification");
        if (loginUser.getSuperiorPlatId() != null) {
            taxCertification.setSuperiorPlatId(loginUser.getSuperiorPlatId());
            taxCertification.setSuperiorPlatName(loginUser.getSuperiorPlatName());
        }
        taxCertification.setAuthStatus(AuthStatus.waitProcess);
        taxCertification.setOrganizeName(organize.getOrganizeName());
        //恢复已删除可匹配的证件数据
        restoreLogicTaxCertification(taxCertification);
        if (taxCertification.getId() == null) {
            taxCertification.setOrganizeId(loginUser.getOrganizeId());
            taxCertification.setOrganizeName(loginUser.getOrganizeName());
            taxCertification.setAddUserId(loginUser.getId());
            taxCertification.setCreateTime(new Date());
            taxCertificationMapper.insert(taxCertification);
        } else {
            taxCertification.setUpdateUserId(loginUser.getId());
            taxCertification.setUpdateTime(new Date());
            taxCertificationMapper.updateById(taxCertification);
        }
        organize.setAgencySignTime(new Date());
        organize.setAgencySignState(Organize.AgencySignState.signed);
        organizeMapper.updateById(organize);
    }

    //-----------------------------------------------------------审核验证----------------------------------------------------------

    /**
     * 验证并更新认证数据
     */
    @Override
    public void verifyAndUpdateAuth(BaseAuth baseAuth, Account loginUser) {
        //ParamUtil.platformCheck(baseAuth, loginUser);
        if (baseAuth instanceof IdCard) {
            IdCard idCard = (IdCard) baseAuth;
            //添加到期预警时间
            if (idCard.getEndTime() != null) {
                idCard.setWarnDate(DateTimeUtil.plusDay(idCard.getEndTime(), -30));
            }
            //重新加密证件号
            String privateStr = EncryptUtils.aesEncrypt(idCard.getIdCardNo().toUpperCase(), null);
            idCard.setIdCardNo(privateStr);//TODO:【加密身份证号】
            boolean success = saveVerifyAuth(idCard, loginUser);
            if (success && idCard.getAccountId() != null) {
                Account account = accountMapper.selectById(idCard.getAccountId());
                account.setSuperiorPlatId(idCard.getSuperiorPlatId());
                account.setSuperiorPlatName(idCard.getSuperiorPlatName());
                account.setName(idCard.getName());
                account.setAddress(idCard.getAddress());
                accountMapper.updateById(account);
                Organize organize = organizeMapper.selectById(account.getOrganizeId());
                if (organize.getManagerUserId().equals(account.getId())) {
                    organize.setManagerUserName(account.getName());
                    if (loginUser.getOrganType() == OrganType.individual) {
                        organize.setOrganizeName(idCard.getName() + "（个体）");
                        organize.setOrganizeTel(loginUser.getPhone());
                    }
                }
                organizeMapper.updateById(organize);
                //认证完成做一些事情
                authComplete(account, AuthData.AuthItem.authIdCard);
            }
        } else if (baseAuth instanceof BusinessLicense) {
            BusinessLicense businessLicense = (BusinessLicense) baseAuth;
            //添加到期预警时间
            if (businessLicense.getValidityEndDate() != null) {
                businessLicense.setWarnDate(DateTimeUtil.plusDay(businessLicense.getValidityEndDate(), -30));
            }
            //重新加密证件号
            String privateStr = EncryptUtils.aesEncrypt(((BusinessLicense) baseAuth).getBusinessNo(), null);
            //TODO:【加密执照编号】
            businessLicense.setBusinessNo(privateStr);
            String privateStr2 = EncryptUtils.aesEncrypt(((BusinessLicense) baseAuth).getLegalCardNo(), null);
            //TODO:【加密法人证件号】
            businessLicense.setLegalCardNo(privateStr2);
            boolean success = saveVerifyAuth(businessLicense, loginUser);
            if (success && businessLicense.getOrganizeId() != null) {
                Organize organize = organizeMapper.selectById(businessLicense.getOrganizeId());
                Account account = accountMapper.selectById(organize.getManagerUserId());
                account.setOrganizeName(businessLicense.getName());
                organize.setOrganizeName(businessLicense.getName());
                organize.setManagerUserPhone(account.getPhone());
                organize.setAddress(businessLicense.getCompanyAddress());
                organizeMapper.updateById(organize);
                //认证完成做一些事情
                authComplete(account, AuthData.AuthItem.authBusinessLicense);
            }
        } else if (baseAuth instanceof DrivingLicense) {
            DrivingLicense drivingLicense = (DrivingLicense) baseAuth;
            //添加到期预警时间
            if (drivingLicense.getValidEndDate() != null) {
                drivingLicense.setWarnDate(DateTimeUtil.plusDay(drivingLicense.getValidEndDate(), -30));
            }
            //重新加密证件号
            String privateStr = EncryptUtils.aesEncrypt(((DrivingLicense) baseAuth).getDrivingLicenseNo(), null);
            //TODO:【加密驾驶证号】
            drivingLicense.setDrivingLicenseNo(privateStr);
            boolean success = saveVerifyAuth(drivingLicense, loginUser);
            if (success && drivingLicense.getAccountId() != null) {
                Account account = accountMapper.selectById(drivingLicense.getAccountId());
                //认证完成做一些事情
                authComplete(account, AuthData.AuthItem.authDrivingLicense);
            }
        } else if (baseAuth instanceof QualificationCert) {
            QualificationCert qualificationCert = (QualificationCert) baseAuth;
            //添加到期预警时间
            if (qualificationCert.getQualificationEndDate() != null) {
                qualificationCert.setWarnDate(DateTimeUtil.plusDay(qualificationCert.getQualificationEndDate(), -30));
            }
            String privateStr = EncryptUtils.aesEncrypt(((QualificationCert) baseAuth).getOccupationalRequirementsNo(), null);
            //TODO:【加密从业资格证号】
            qualificationCert.setOccupationalRequirementsNo(privateStr);
            boolean success = saveVerifyAuth(qualificationCert, loginUser);
            if (success && qualificationCert.getAccountId() != null) {
                Account account = accountMapper.selectById(qualificationCert.getAccountId());
                //认证完成做一些事情
                authComplete(account, AuthData.AuthItem.authQualificationCert);
            }
        } else if (baseAuth instanceof TransBusinessLicense) {
            TransBusinessLicense transBusinessLicense = (TransBusinessLicense) baseAuth;
            //添加到期预警时间
            if (transBusinessLicense.getTransBusinessLicenseEndDate() != null) {
                transBusinessLicense.setWarnDate(DateTimeUtil.plusDay(transBusinessLicense.getTransBusinessLicenseEndDate(), -30));
            }
            //重新加密证件号
            String privateStr = EncryptUtils.aesEncrypt(((TransBusinessLicense) baseAuth).getTransBusinessLicenseNo(), null);
            //TODO:【加密经营许可证号】
            transBusinessLicense.setTransBusinessLicenseNo(privateStr);
            saveVerifyAuth(transBusinessLicense, loginUser);
        } else if (baseAuth instanceof StampCompanySeal) {
            StampCompanySeal stampCompanySeal = (StampCompanySeal) baseAuth;
            boolean success = saveVerifyAuth(stampCompanySeal, loginUser);
            if (success && stampCompanySeal.getOrganizeId() != null) {
                Organize organize = organizeMapper.selectById(stampCompanySeal.getOrganizeId());
                organize.setSignatureImg(stampCompanySeal.getCompanySeal());
                organize.setSignatureId(stampCompanySeal.getId());
                organizeMapper.updateById(organize);
            }
        } else if (baseAuth instanceof StampPersonalSignet) {
            StampPersonalSignet StampPersonalSignet = (StampPersonalSignet) baseAuth;
            boolean success = saveVerifyAuth(StampPersonalSignet, loginUser);
            if (success && StampPersonalSignet.getOrganizeId() != null) {
                Organize organize = organizeMapper.selectById(StampPersonalSignet.getOrganizeId());
                organize.setSignatureImg(StampPersonalSignet.getPersonalSignet());
                organize.setSignatureId(StampPersonalSignet.getId());
                organizeMapper.updateById(organize);
            }
        } else if (baseAuth instanceof TaxCertification) {
            TaxCertification taxCertification = (TaxCertification) baseAuth;
            saveVerifyAuth(taxCertification, loginUser);
        }
    }

    /**
     * 审核保存公共方法
     */
    private boolean saveVerifyAuth(BaseAuth baseAuth, Account loginUser) {
        if (baseAuth.getAuthStatus() != AuthStatus.authSuccess && baseAuth.getAuthStatus() != AuthStatus.authFail) {
            throw new BusinessException("审核结果有误!");
        }
        //认证结果
        boolean authResult = true;
        if (baseAuth.getAuthStatus() != AuthStatus.authSuccess) authResult = false;
        if (baseAuth instanceof IdCard) {
            IdCard idCard = idCardMapper.selectById(baseAuth.getId());
            idCard.setIdCardFrontImg(((IdCard) baseAuth).getIdCardFrontImg());
            idCard.setIdCardBackImg(((IdCard) baseAuth).getIdCardBackImg());
            idCard.setIdCardPersonImg(((IdCard) baseAuth).getIdCardPersonImg());
            idCard.setIdCardNo(((IdCard) baseAuth).getIdCardNo());
            idCard.setName(((IdCard) baseAuth).getName());
            idCard.setAddress(((IdCard) baseAuth).getAddress());
            idCard.setStartTime(((IdCard) baseAuth).getStartTime());
            idCard.setEndTime(((IdCard) baseAuth).getEndTime());
            idCard.setAuthStatus(baseAuth.getAuthStatus());
            idCard.setFailedMsg(baseAuth.getFailedMsg());
            idCard.setAutTime(new Date());
            idCard.setAutUserId(loginUser.getId());
            idCardMapper.updateById(idCard);
            if (!authResult) {
                Account account = accountMapper.selectById(idCard.getAccountId());
                String text = String.format("尊敬的用户您好，您的身份证认证失败了，请尽快重新认证。失败原因:%s", baseAuth.getFailedMsg());
                ParamUtil.isSuccess(messageRemote.sendSystemNotify(account.getId(), text, null));
            }
        }
        if (baseAuth instanceof BusinessLicense) {
            BusinessLicense businessLicense = businessLicenseMapper.selectById(baseAuth.getId());
            businessLicense.setCompanyImg(((BusinessLicense) baseAuth).getCompanyImg());
            businessLicense.setLegalIdCardFontImg(((BusinessLicense) baseAuth).getLegalIdCardFontImg());
            businessLicense.setLegalIdCardBackImg(((BusinessLicense) baseAuth).getLegalIdCardBackImg());
            businessLicense.setOrganizeName(((BusinessLicense) baseAuth).getOrganizeName());
            businessLicense.setBusinessNo(((BusinessLicense) baseAuth).getBusinessNo());
            businessLicense.setLegalCardNo(((BusinessLicense) baseAuth).getLegalCardNo());
            businessLicense.setName(((BusinessLicense) baseAuth).getName());
            businessLicense.setValidityEndDate(((BusinessLicense) baseAuth).getValidityEndDate());
            businessLicense.setValidityStartDate(((BusinessLicense) baseAuth).getValidityStartDate());
            businessLicense.setBcValidityStartDate(((BusinessLicense) baseAuth).getBcValidityStartDate());
            businessLicense.setBcValidityEndDate(((BusinessLicense) baseAuth).getBcValidityEndDate());
            businessLicense.setLegalName(((BusinessLicense) baseAuth).getLegalName());
            businessLicense.setAuthStatus(baseAuth.getAuthStatus());
            businessLicense.setFailedMsg(baseAuth.getFailedMsg());
            businessLicense.setAutTime(new Date());
            businessLicense.setAutUserId(loginUser.getId());
            businessLicenseMapper.updateById(businessLicense);
            if (!authResult) {
                Organize organize = organizeMapper.selectById(businessLicense.getOrganizeId());
                String text = String.format("尊敬的用户您好，您的营业执照认证失败了，请尽快重新认证。失败原因:%s", baseAuth.getFailedMsg());
                ParamUtil.isSuccess(messageRemote.sendSystemNotify(organize.getManagerUserId(), text, null));
            }
        }
        if (baseAuth instanceof DrivingLicense) {
            DrivingLicense drivingLicense = drivingLicenseMapper.selectById(baseAuth.getId());
            drivingLicense.setDrivingLicenseImg(((DrivingLicense) baseAuth).getDrivingLicenseImg());
            drivingLicense.setDrivingLicenseName(((DrivingLicense) baseAuth).getDrivingLicenseName());
            drivingLicense.setDrivingLicenseNo(((DrivingLicense) baseAuth).getDrivingLicenseNo());
            drivingLicense.setDrivingLicenseType(((DrivingLicense) baseAuth).getDrivingLicenseType());
            drivingLicense.setIssuingOrganizations(((DrivingLicense) baseAuth).getIssuingOrganizations());
            drivingLicense.setValidStartDate(((DrivingLicense) baseAuth).getValidStartDate());
            drivingLicense.setValidEndDate(((DrivingLicense) baseAuth).getValidEndDate());
            drivingLicense.setAuthStatus(baseAuth.getAuthStatus());
            drivingLicense.setAutTime(new Date());
            drivingLicense.setFailedMsg(baseAuth.getFailedMsg());
            drivingLicense.setAutUserId(loginUser.getId());
            drivingLicenseMapper.updateById(drivingLicense);
            // ### 触发：准备创建/更新省运管数据
            Account localAccount = accountMapper.selectById(drivingLicense.getAccountId());
            localAccount.setTmsDriverDataState(Account.TmsDriverDataState.creating);
            accountService.updateById(localAccount);
            if (!authResult) {
                Account account = accountMapper.selectById(drivingLicense.getAccountId());
                String text = String.format("尊敬的用户您好，您的驾驶证认证失败了，请尽快重新认证。失败原因:%s", baseAuth.getFailedMsg());
                ParamUtil.isSuccess(messageRemote.sendSystemNotify(account.getId(), text, null));
            }
        }
        if (baseAuth instanceof TransBusinessLicense) {
            TransBusinessLicense transBusinessLicense = transBusinessLicenseMapper.selectById(baseAuth.getId());
            transBusinessLicense.setTransBusinessLicenseImg(((TransBusinessLicense) baseAuth).getTransBusinessLicenseImg());
            transBusinessLicense.setCompanyName(((TransBusinessLicense) baseAuth).getCompanyName());
            transBusinessLicense.setTransBusinessLicenseNo(((TransBusinessLicense) baseAuth).getTransBusinessLicenseNo());
            transBusinessLicense.setTransBusinessLicenseEndDate(((TransBusinessLicense) baseAuth).getTransBusinessLicenseEndDate());
            transBusinessLicense.setTransBusinessLicenseScope(((TransBusinessLicense) baseAuth).getTransBusinessLicenseScope());
            transBusinessLicense.setAuthStatus(baseAuth.getAuthStatus());
            transBusinessLicense.setFailedMsg(baseAuth.getFailedMsg());
            transBusinessLicense.setAutTime(new Date());
            transBusinessLicense.setAutUserId(loginUser.getId());
            transBusinessLicenseMapper.updateById(transBusinessLicense);
            if (!authResult) {
                Organize organize = organizeMapper.selectById(transBusinessLicense.getOrganizeId());
                String text = String.format("尊敬的用户您好，您的道路运输经营许可证认证失败了，请尽快重新认证。失败原因:%s", baseAuth.getFailedMsg());
                ParamUtil.isSuccess(messageRemote.sendSystemNotify(organize.getManagerUserId(), text, null));
            }
        }
        if (baseAuth instanceof QualificationCert) {
            QualificationCert qualificationCert = qualificationCertMapper.selectById(baseAuth.getId());
            qualificationCert.setQualificationPhotoImg(((QualificationCert) baseAuth).getQualificationPhotoImg());
            qualificationCert.setOccupationalRequirementsNo(((QualificationCert) baseAuth).getOccupationalRequirementsNo());
            qualificationCert.setQualificationCategories(((QualificationCert) baseAuth).getQualificationCategories());
            qualificationCert.setQualificationArea(((QualificationCert) baseAuth).getQualificationArea());
            qualificationCert.setQualificationEndDate(((QualificationCert) baseAuth).getQualificationEndDate());
            qualificationCert.setAuthStatus(baseAuth.getAuthStatus());
            qualificationCert.setFailedMsg(baseAuth.getFailedMsg());
            qualificationCert.setAutTime(new Date());
            qualificationCert.setAutUserId(loginUser.getId());
            qualificationCertMapper.updateById(qualificationCert);
            // ### 触发：准备创建/更新省运管数据
            Account localAccount = accountMapper.selectById(qualificationCert.getAccountId());
            localAccount.setTmsDriverDataState(Account.TmsDriverDataState.creating);
            accountService.updateById(localAccount);
            if (!authResult) {
                Account account = accountMapper.selectById(qualificationCert.getAccountId());
                String text = String.format("尊敬的用户您好，您的从业资格证认证失败了，请尽快重新认证。失败原因:%s", baseAuth.getFailedMsg());
                ParamUtil.isSuccess(messageRemote.sendSystemNotify(account.getId(), text, null));
            }
        }
        if (baseAuth instanceof StampPersonalSignet) {
            StampPersonalSignet stampPersonalSignet = stampPersonalSignetMapper.selectById(baseAuth.getId());
            stampPersonalSignet.setAuthStatus(baseAuth.getAuthStatus());
            stampPersonalSignet.setPersonalSignet(((StampPersonalSignet) baseAuth).getPersonalSignet());
            stampPersonalSignet.setOrganizeName(((StampPersonalSignet) baseAuth).getOrganizeName());
            stampPersonalSignetMapper.updateById(stampPersonalSignet);
            if (!authResult) {
                Organize organize = organizeMapper.selectById(stampPersonalSignet.getOrganizeId());
                String text = String.format("尊敬的用户您好，您的签名认证失败了，请尽快重新认证。失败原因:%s", baseAuth.getFailedMsg());
                ParamUtil.isSuccess(messageRemote.sendSystemNotify(organize.getManagerUserId(), text, null));
            }

        }
        if (baseAuth instanceof StampCompanySeal) {
            StampCompanySeal stampCompanySeal = stampCompanySealMapper.selectById(baseAuth.getId());
            stampCompanySeal.setAuthStatus(baseAuth.getAuthStatus());
            stampCompanySeal.setCompanySeal(((StampCompanySeal) baseAuth).getCompanySeal());
            stampCompanySeal.setOrganizeName(((StampCompanySeal) baseAuth).getOrganizeName());
            stampCompanySealMapper.updateById(stampCompanySeal);
            if (!authResult) {
                Organize organize = organizeMapper.selectById(stampCompanySeal.getOrganizeId());
                String text = String.format("尊敬的用户您好，您的印章认证失败了，请尽快重新认证。失败原因:%s", baseAuth.getFailedMsg());
                ParamUtil.isSuccess(messageRemote.sendSystemNotify(organize.getManagerUserId(), text, null));
            }
        }
        if (baseAuth instanceof TaxCertification) {
            TaxCertification taxCertification = taxCertificationMapper.selectById(baseAuth.getId());
            taxCertification.setAuthStatus(baseAuth.getAuthStatus());
            taxCertification.setTaxCertificationImg(((TaxCertification) baseAuth).getTaxCertificationImg());
            taxCertification.setOrganizeName(((TaxCertification) baseAuth).getOrganizeName());
            taxCertificationMapper.updateById(taxCertification);
            if (!authResult) {
                Organize organize = organizeMapper.selectById(taxCertification.getOrganizeId());
                String text = String.format("尊敬的用户您好，您的税务认证审核失败，请尽快重新认证。失败原因:%s", baseAuth.getFailedMsg());
                ParamUtil.isSuccess(messageRemote.sendSystemNotify(organize.getManagerUserId(), text, null));
            }
        }
        return authResult;
    }

    /**
     * 认证完成
     */
    private void authComplete(Account account, AuthData.AuthItem authItem) {
//        switch (authItem) {
//            case authIdCard:
//                String text = "尊敬的用户您好，您的身份证已认证成功！您现在可以登录APP进行后续功能操作，感谢您对平台的信任。";
//                ParamUtil.isSuccess(messageRemote.sendSystemNotify(account.getId(), text, null));
//                break;
//            case authBusinessLicense:
//                String BusinessLicenseText = "尊敬的用户您好，您的企业的营业执照已认证成功！您现在可以登录APP进行后续功能操作，感谢您对平台的信任。";
//                ParamUtil.isSuccess(messageRemote.sendSystemNotify(account.getId(), BusinessLicenseText, null));
//                //TODO:更新 民生银行子账户信息
//                break;
//            case authDrivingLicense:
//                String DrivingLicenseText = "尊敬的用户您好，您的驾驶证已认证成功！您现在可以登录APP进行后续功能操作，感谢您对平台的信任。";
//                ParamUtil.isSuccess(messageRemote.sendSystemNotify(account.getId(), DrivingLicenseText, null));
//                break;
//            case authQualificationCert:
//                String QualificationCertText = "尊敬的用户您好，您的道路运输从业资格证已认证成功！您现在可以登录APP进行后续功能操作，感谢您对平台的信任。";
//                ParamUtil.isSuccess(messageRemote.sendSystemNotify(account.getId(), QualificationCertText, null));
//                //TODO:保存或更新 驾驶员信息单
//                break;
//            default:
//                break;
//        }
    }

    /**
     * 分页数据解密
     */
    private <T> PageData<T> authPageDecrypt(PageData<T> page) {
        for (T data : page.getList()) {
            if (data instanceof IdCard) {
                ((IdCard) data).setIdCardNo(EncryptUtils.aesDecrypt(((IdCard) data).getIdCardNo(), null));
            } else if (data instanceof BusinessLicense) {
                ((BusinessLicense) data).setBusinessNo(EncryptUtils.aesDecrypt(((BusinessLicense) data).getBusinessNo(), null));
                ((BusinessLicense) data).setLegalCardNo(EncryptUtils.aesDecrypt(((BusinessLicense) data).getLegalCardNo(), null));
            } else if (data instanceof DrivingLicense) {
                ((DrivingLicense) data).setDrivingLicenseNo(EncryptUtils.aesDecrypt(((DrivingLicense) data).getDrivingLicenseNo(), null));
            } else if (data instanceof TransBusinessLicense) {
                ((TransBusinessLicense) data).setTransBusinessLicenseNo(EncryptUtils.aesDecrypt(((TransBusinessLicense) data).getTransBusinessLicenseNo(), null));
            } else if (data instanceof QualificationCert) {
                ((QualificationCert) data).setOccupationalRequirementsNo(EncryptUtils.aesDecrypt(((QualificationCert) data).getOccupationalRequirementsNo(), null));
            }
        }
        return page;
    }

    /**
     * 证件预期及其过期提醒
     */
    @Override
    public void autoCertificatesOverdue() {
        //身份证
        QueryWrapper<IdCard> idCardQueryWrapper = new QueryWrapper<>();
        idCardQueryWrapper.le("end_time", DateTimeUtil.plusDay(new Date(), 30));
        List<IdCard> idCardList = idCardMapper.selectList(idCardQueryWrapper);
        for (IdCard idCard : idCardList) {
            String text = "尊敬的用户您好，您预留的身份证信息即将过期，为不影响您的业务正常运行，请您尽快更新证件！";
            if (idCard.getEndTime().compareTo(new Date()) <= 0) {
                text = "尊敬的用户您好，您预留的身份证信息已过期，您暂时不能进行相关业务，请您尽快更新证件！";
                //无论延期还是过期，货源自动下线，延期期间也不能上线
                orderRemote.recallGoodsOrderByAccountId(idCard.getAccountId());
                //检查未完成订单，存在延期，不存在过期，
                Boolean exist = ParamUtil.isSuccess(orderRemote.checkExistRunOrderByAccountId(idCard.getAccountId()));
                idCard.setAuthStatus(exist ? AuthStatus.authDelay : AuthStatus.authExpire);
                idCardMapper.updateById(idCard);
            }
            messageRemote.sendSystemNotify(idCard.getAccountId(), text, null);
        }

        //营业执照
        QueryWrapper<BusinessLicense> businessLicenseQueryWrapper = new QueryWrapper<>();
        businessLicenseQueryWrapper.le("validity_end_date", DateTimeUtil.plusDay(new Date(), 30));
        businessLicenseQueryWrapper.or().le("bc_validity_end_date", DateTimeUtil.plusDay(new Date(), 30));
        List<BusinessLicense> businessLicenseList = businessLicenseMapper.selectList(businessLicenseQueryWrapper);
        for (BusinessLicense businessLicense : businessLicenseList) {
            String text = "尊敬的用户您好，您预留的营业执照信息即将过期，为不影响您的业务正常运行，请您尽快更新证件！";
            if (businessLicense.getValidityEndDate().compareTo(new Date()) <= 0 || businessLicense.getBcValidityEndDate().compareTo(new Date()) <= 0) {
                text = "尊敬的用户您好，您预留的营业执照信息已过期，您暂时不能进行相关业务，请您尽快更新证件！";
                //无论延期还是过期，货源自动下线，延期期间也不能上线
                orderRemote.recallGoodsOrderByOrganizeId(businessLicense.getOrganizeId());
                //检查未完成订单，存在延期，不存在过期，
                Boolean exist = ParamUtil.isSuccess(orderRemote.checkExistRunOrderByOrganizeId(businessLicense.getOrganizeId()));
                businessLicense.setAuthStatus(exist ? AuthStatus.authDelay : AuthStatus.authExpire);
                businessLicenseMapper.updateById(businessLicense);
            }
            Organize organize = organizeMapper.selectById(businessLicense.getOrganizeId());
            messageRemote.sendSystemNotify(organize.getManagerUserId(), text, null);
        }

        //驾驶证
        QueryWrapper<DrivingLicense> drivingLicenseQueryWrapper = new QueryWrapper<>();
        drivingLicenseQueryWrapper.le("valid_end_date", DateTimeUtil.plusDay(new Date(), 30));
        List<DrivingLicense> drivingLicenseList = drivingLicenseMapper.selectList(drivingLicenseQueryWrapper);
        for (DrivingLicense drivingLicense : drivingLicenseList) {
            String text = "尊敬的用户您好，您预留的驾驶证信息即将过期，为不影响您的业务正常运行，请您尽快更新证件！";
            if (drivingLicense.getValidEndDate().compareTo(new Date()) <= 0) {
                text = "尊敬的用户您好，您预留的驾驶证信息已过期，您暂时不能进行相关业务，请您尽快更新证件！";
                Boolean exist = ParamUtil.isSuccess(orderRemote.checkExistRunOrderByAccountId(drivingLicense.getAccountId()));
                drivingLicense.setAuthStatus(exist ? AuthStatus.authDelay : AuthStatus.authExpire);
                drivingLicenseMapper.updateById(drivingLicense);
            }
            messageRemote.sendSystemNotify(drivingLicense.getAccountId(), text, null);
        }

        //从业资格证
        QueryWrapper<QualificationCert> qualificationCertQueryWrapper = new QueryWrapper<>();
        qualificationCertQueryWrapper.le("qualification_end_date", DateTimeUtil.plusDay(new Date(), 30));
        List<QualificationCert> qualificationCertList = qualificationCertMapper.selectList(qualificationCertQueryWrapper);
        for (QualificationCert qualificationCert : qualificationCertList) {
            String text = "尊敬的用户您好，您预留的从业资格证信息即将过期，为不影响您的业务正常运行，请您尽快更新证件！";
            if (qualificationCert.getQualificationEndDate().compareTo(new Date()) <= 0) {
                text = "尊敬的用户您好，您预留的从业资格证信息已过期，您暂时不能进行相关业务，请您尽快更新证件！";
                Boolean exist = ParamUtil.isSuccess(orderRemote.checkExistRunOrderByAccountId(qualificationCert.getAccountId()));
                qualificationCert.setAuthStatus(exist ? AuthStatus.authDelay : AuthStatus.authExpire);
                qualificationCertMapper.updateById(qualificationCert);
            }
            messageRemote.sendSystemNotify(qualificationCert.getAccountId(), text, null);
        }

        //道路运输经营许可证
        QueryWrapper<TransBusinessLicense> transBusinessLicenseQueryWrapper = new QueryWrapper<>();
        transBusinessLicenseQueryWrapper.le("trans_business_license_end_date", DateTimeUtil.plusDay(new Date(), 30));
        List<TransBusinessLicense> transBusinessLicenseList = transBusinessLicenseMapper.selectList(transBusinessLicenseQueryWrapper);
        for (TransBusinessLicense transBusinessLicense : transBusinessLicenseList) {
            String text = "尊敬的用户您好，您预留的道路运输经营许可证信息即将过期，为不影响您的业务正常运行，请您尽快更新证件！";
            if (transBusinessLicense.getTransBusinessLicenseEndDate().compareTo(new Date()) <= 0) {
                text = "尊敬的用户您好，您预留的道路运输经营许可证信息已过期，您暂时不能进行相关业务，请您尽快更新证件！";
                //检查未完成订单，存在延期，不存在过期，
                Boolean exist = ParamUtil.isSuccess(orderRemote.checkExistRunOrderByOrganizeId(transBusinessLicense.getOrganizeId()));
                transBusinessLicense.setAuthStatus(exist ? AuthStatus.authDelay : AuthStatus.authExpire);
                transBusinessLicenseMapper.updateById(transBusinessLicense);
            }
            Organize organize = organizeMapper.selectById(transBusinessLicense.getOrganizeId());
            messageRemote.sendSystemNotify(organize.getManagerUserId(), text, null);
        }
    }

    //-------------------------------------------------------------逻辑删除区--------------------------------------------------------

    @Override
    public void deleteIdCardById(IdCard idCard) {
        idCardMapper.deleteById(idCard);
    }

    @Override
    public void deleteDrivingLicenseById(DrivingLicense drivingLicense) {
        drivingLicenseMapper.deleteById(drivingLicense);
    }

    @Override
    public void deleteQualificationCertById(QualificationCert qualificationCert) {
        qualificationCertMapper.deleteById(qualificationCert);
    }

    @Override
    public void deleteBusinessLicenseById(BusinessLicense businessLicense) {
        businessLicenseMapper.deleteById(businessLicense);
    }

    @Override
    public void deleteTransBusinessLicense(TransBusinessLicense transBusinessLicense) {
        transBusinessLicenseMapper.deleteById(transBusinessLicense);
    }

    @Override
    public void deleteStampPersonalSignet(StampPersonalSignet stampPersonalSignet) {
        stampPersonalSignetMapper.deleteById(stampPersonalSignet);
    }

    @Override
    public void deleteStampCompanySeal(StampCompanySeal stampCompanySeal) {
        stampCompanySealMapper.deleteById(stampCompanySeal);
    }

    @Override
    public void deleteTaxCertification(TaxCertification taxCertification) {
        taxCertificationMapper.deleteById(taxCertification);
    }


    //-------------------------------------------------------------逻辑恢复区--------------------------------------------------------

    @Override
    public void restoreLogicIdCardByNo(IdCard idCard) {
        QueryWrapper<IdCard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card_no", idCard.getIdCardNo());
        queryWrapper.eq("is_deleted", 1);
        IdCard local = idCardMapper.selectOne(queryWrapper);
        if (local == null) return;
        idCard.setIsDeleted(0);
        idCard.setId(local.getId());
    }

    @Override
    public void restoreLogicDrivingLicenseByNo(DrivingLicense drivingLicense) {
        QueryWrapper<DrivingLicense> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("driving_license_no", drivingLicense.getDrivingLicenseNo());
        queryWrapper.eq("is_deleted", 1);
        DrivingLicense local = drivingLicenseMapper.selectOne(queryWrapper);
        if (local == null) return;
        drivingLicense.setIsDeleted(0);
        drivingLicense.setId(local.getId());
    }

    @Override
    public void restoreLogicQualificationCertByNo(QualificationCert qualificationCert) {
        QueryWrapper<QualificationCert> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("occupational_requirements_no", qualificationCert.getOccupationalRequirementsNo());
        queryWrapper.eq("is_deleted", 1);
        QualificationCert local = qualificationCertMapper.selectOne(queryWrapper);
        if (local == null) return;
        qualificationCert.setIsDeleted(0);
        qualificationCert.setId(local.getId());
    }

    @Override
    public void restoreLogicBusinessLicenseByNo(BusinessLicense businessLicense) {
        QueryWrapper<BusinessLicense> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("business_no", businessLicense.getBusinessNo());
        queryWrapper.eq("is_deleted", 1);
        BusinessLicense local = businessLicenseMapper.selectOne(queryWrapper);
        if (local == null) return;
        businessLicense.setIsDeleted(0);
        businessLicense.setId(local.getId());
    }

    @Override
    public void restoreLogicTransBusinessLicenseByNo(TransBusinessLicense transBusinessLicense) {
        QueryWrapper<TransBusinessLicense> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("trans_business_license_no", transBusinessLicense.getTransBusinessLicenseNo());
        queryWrapper.eq("is_deleted", 1);
        TransBusinessLicense local = transBusinessLicenseMapper.selectOne(queryWrapper);
        if (local == null) return;
        transBusinessLicense.setIsDeleted(0);
        transBusinessLicense.setId(local.getId());
    }

    @Override
    public void restoreLogicStampPersonalSignet(StampPersonalSignet stampPersonalSignet) {
        QueryWrapper<StampPersonalSignet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organize_name", stampPersonalSignet.getOrganizeName());
        queryWrapper.eq("is_deleted", 1);
        StampPersonalSignet local = stampPersonalSignetMapper.selectOne(queryWrapper);
        if (local == null) return;
        stampPersonalSignet.setIsDeleted(0);
        stampPersonalSignet.setId(local.getId());
    }

    @Override
    public void restoreLogicStampCompanySeal(StampCompanySeal stampCompanySeal) {
        QueryWrapper<StampCompanySeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organize_name", stampCompanySeal.getOrganizeName());
        queryWrapper.eq("is_deleted", 1);
        StampCompanySeal local = stampCompanySealMapper.selectOne(queryWrapper);
        if (local == null) return;
        stampCompanySeal.setIsDeleted(0);
        stampCompanySeal.setId(local.getId());
    }

    @Override
    public void restoreLogicTaxCertification(TaxCertification taxCertification) {
        QueryWrapper<TaxCertification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("organize_name", taxCertification.getOrganizeName());
        queryWrapper.eq("is_deleted", 1);
        TaxCertification local = taxCertificationMapper.selectOne(queryWrapper);
        if (local == null) return;
        taxCertification.setIsDeleted(0);
        taxCertification.setId(local.getId());
    }


}
